package edu.mercer.sse.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.google.common.base.Optional;

import edu.mercer.sse.app.Config;

/**
 * 
 * JDBC Database connection.<p>
 *
 * Connects using credentials specified in application properties XML.<p>
 *
 * @see Config
 *
 */

public class DBConnector
{
	private Optional<Connection> _db = Optional.absent();
	
	
	public DBConnector(){}//constructor
	
	
	public DBConnector connect() throws SQLException
	{
		disconnect();
		
		init();
		
		return this;
		
	}//method
	
	
	public DBConnector disconnect() throws SQLException
	{
		if( _db.isPresent() ) _db.get().close();
		
		return this;
		
	}//method
	
	
	public Connection con() throws SQLException
	{
		return _db.or( init() );
		
	}//method

	
	private Connection init() throws SQLException
	{
		DriverManager.registerDriver( new com.mysql.jdbc.Driver() );
		
		_db = Optional.of( DriverManager.getConnection(
				"jdbc:mysql://" +
						Config.settings()
							  .getProperty("database-host") 
						+ "/" + 
						Config.settings()
							  .getProperty("database-name") 
						+ "?",						
						Config.settings()
							  .getProperty("database-username"),
						Config.settings()
							  .getProperty("database-password")));			
		
		return _db.get();
		
	}//method
	
	
}//class
